package com.xmmj.baselibrary.network;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;

/**
 * 上传文件的请求体
 */
public class UploadRequestBody extends RequestBody {
    private final File file;
    private final UploadCallback callback;
    private static final int DEFAULT_BUFFER_SIZE = 2048;

    public UploadRequestBody(final File file, final UploadCallback callback) {
        this.file = file;
        this.callback = callback;
    }

    @Override
    public MediaType contentType() {
        return MediaType.parse("image/*");
    }

    @Override
    public long contentLength() {
        return file.length();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        long fileLength = file.length();
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        FileInputStream in = new FileInputStream(file);
        long uploaded = 0;
        try {
            int read;
            while ((read = in.read(buffer)) != -1) {
                uploaded += read;
                sink.write(buffer, 0, read);
                if (callback != null)
                    callback.onProgressUpdate((int) (uploaded * 100 / fileLength));
            }
            if (callback != null)
                callback.onCompleted(file);
        } catch (Exception e) {
            if (callback != null)
                callback.onUpLoadFail(e);
        } finally {
            in.close();
        }
    }

    public interface UploadCallback {
        /**
         * 上传进度
         *
         * @param percentage 进度
         */
        void onProgressUpdate(int percentage);

        /**
         * 上传完成
         *
         * @param file 文件
         */
        void onCompleted(File file);

        /**
         * 上传失败
         *
         * @param throwable 异常
         */
        void onUpLoadFail(Throwable throwable);
    }
}
